/**
 * Created by tdzl2003 on 8/25/16.
 */

import {EventEmitter} from 'fbemitter';
import md5 from './md5';
import RPC, {get, post, saveToken, clearToken} from './rpc';

const Auth = new EventEmitter;
export default Auth;
const emit = Auth.emit.bind(Auth);

let userInfo = null;

export async function login({account, pwd}) {
  try {
    const {token} = await post('/admin/acc/login', {
      account,
      pwd: md5(pwd),
    });
    saveToken(token);
    await loadUserInfo();
  } catch (err) {
    if (__DEV__) {
      console.error(err);
    }
    switch (err.code) {
      case 403: throw new Error('用户名或密码错误');
      default: throw new Error('登录失败');
    }
  }
  emit('userInfoChanged', userInfo);
}

export async function logout() {
  clearToken();
  userInfo = null;
  emit('userInfoChanged', userInfo);
}

RPC.addListener('invalidToken', logout);

export function isLogined() {
  return userInfo !== null;
}

export function getUserInfo() {
  return userInfo;
}

export async function loadUserInfo() {
  userInfo = await get('/admin/acc/me');
  emit('userInfoChanged', userInfo);
}

export async function changeMyPwd({oldPwd, newPwd}) {
  await post('/admin/acc/me/setPwd', {oldPwd:md5(oldPwd), newPwd:md5(newPwd)});
  setTimeout(()=>alert('修改成功'));
}
